/**
 * Copyright (c) 2011 Technical Centre Radio Systems Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ua.tcrs.tabula.util;

import java.util.Iterator;

public class Joiner {
	private final String separator;
	public Joiner( String separator ) {
		this.separator = separator;
	}
	public Joiner( char separator ) {
		this.separator = String.valueOf( separator );
	}
	public String join( Object... parts ) {
		StringBuilder sb = new StringBuilder();
		if ( parts.length > 0 ) {
			if ( parts[0] != null ) sb.append( (parts[0] instanceof CharSequence) ? (CharSequence) parts[0] : parts[0].toString() );
			for ( int idx=1; idx<parts.length; idx++ ) {
				if ( parts[idx] != null ) {
					sb.append( separator );
					sb.append( (parts[idx] instanceof CharSequence) ? (CharSequence) parts[idx] : parts[idx].toString() );
				}
			}
		}
		return sb.toString();
	}
	public String join( Iterable<?> parts ) {
		StringBuilder sb = new StringBuilder();
		Iterator<?> iterator = parts.iterator();
		if ( iterator.hasNext() ) {
			sb.append( iterator.next().toString() );
			while ( iterator.hasNext() ) {
				sb.append( separator );
				sb.append( iterator.next().toString() );
			}
		}
		return sb.toString();
	}
}

